import concurrent.futures
import glob
import logging
import os
import time
from pathlib import Path

import pytest
from tools.decorators import log_decorator
from tools.上传至erp import 上传ERP
from tools.合并excel import merge_excel_files
from tools.获取投诉数据 import 获取投诉数据


@pytest.mark.run(order=1)
@log_decorator
def 获取投诉数据_test(username, date, date_start):
    dfs = username
    for df in dfs:
        futures = []
        logging.info('创建线程池')
        with concurrent.futures.ThreadPoolExecutor() as executor:
            for index, row in enumerate(df.iterrows()):
                port = index + 1 + 9600
                print(port)
                future = executor.submit(获取投诉数据, row[1]['店铺名称'], row[1]['账号'], row[1]['密码'], port, date, date_start)
                futures.append(future)
                logging.info(f"提交{row[1]['店铺名称']}线程执行")
            executor.shutdown()
            for future in futures:
                # 获取线程的返回值或抛出异常
                future.result()
        time.sleep(5)
    logging.info('所有线程执行完毕')
    file_path = f"C:\\投诉模板\\{date}"
    input_files = glob.glob(os.path.join(file_path, "*.xlsx"))
    output_file = f"C:\\投诉模板\\{date}\\投诉模板.xlsx"
    if not Path(output_file).exists():
        logging.info('开始合并Excel')
        merge_excel_files(input_files, output_file)
        logging.info('合并Excel成功')
        上传ERP(output_file)
